package ejb.cbm.admin.session;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;

import ejb.cbm.admin.bean.ParametroBean;
import ejb.cbm.admin.entity.ParametroEntity;
import ejb.cbm.admin.local.ParametroSessionLocal;

////@Stateless
@Service("parametroSessionLocal")
public class ParametroSession extends HibernateDaoSupport implements ParametroSessionLocal {
	
	static Logger logger = Logger.getLogger(ParametroSession.class.getName());
	//property constants
	public static final String DESCRIPCION = "descripcion";
	public static final String VALORNUMERICO = "valornumerico";
	public static final String VALORALFANUMERICO = "valoralfanumerico";
	public static final String FLAGACTIVO = "flagactivo";
	public static final String USUARIOREGISTRO = "usuarioregistro";
	public static final String USUARIOMODIFICACION = "usuariomodificacion";


    //@PersistenceContext 
    //private EntityManager entityManager;
	@Autowired
	public ParametroSession(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
    public void save(ParametroEntity transientInstance) {
    	logger.info("saving ParametroEntity instance");
        try {
            getSession().persist(transientInstance);
            logger.info("save successful");
        } catch (RuntimeException re) {
        	logger.fatal("save failed");
            throw re;
        }
    }
    
    public void delete(ParametroEntity persistentInstance) {
    	logger.info("deleting ParametroEntity instance");
        try {
            getSession().delete(persistentInstance);
            logger.info("delete successful");
        } catch (RuntimeException re) {
        	logger.fatal("delete failed");
            throw re;
        }
    }
    
    public ParametroEntity update(ParametroEntity detachedInstance) {
    	logger.info("updating ParametroEntity instance");
        try {
            ParametroEntity result = (ParametroEntity) getSession().merge(detachedInstance);
            logger.info("update successful");
            return result;
        } catch (RuntimeException re) {
        	logger.fatal("update failed");
            throw re;
        }
    }
    
    public ParametroEntity findById( Long id) {
    	logger.info("finding ParametroEntity instance with id: " + id);
        try {
            ParametroEntity instance = (ParametroEntity) getSession().get(ParametroEntity.class, id);
            return instance;
        } catch (RuntimeException re) {
        	logger.fatal("find failed");
            throw re;
        }
    }
    
    //@SuppressWarnings("unchecked")
    public List<ParametroEntity> findByProperty(String propertyName, Object value) {
    	logger.info("finding ParametroEntity instance with property: " + propertyName
    						+ ", value: " + value);
		try {
			String queryString = "select model from ParametroEntity model where model." 
			 						+ propertyName + "= :propertyValue";
			return getSession().createQuery(queryString)
 				.setParameter("propertyValue", value).list();
		} catch (RuntimeException re) {
			logger.fatal("find by property name failed");
			throw re;
		}
	}
    
    public List<ParametroEntity> findByCodigoTipoParametro(Object value) {    	
		try {
			String queryString = "select model from ParametroEntity model where model.tipoparametro.codigotipoparametro" 
			 						+"= :propertyValue";
			return getSession().createQuery(queryString)
 				.setParameter("propertyValue", value).list();
		} catch (RuntimeException re) {
			logger.info("find by property name failed");
			throw re;
		}
	}
    
    
    
    //@SuppressWarnings("unchecked")
	public ParametroEntity findParametro(Long codigoTipo, Double valorParametro){
		logger.fatal("findByFiltro RegistroIngresoEntity instance");
		StringBuilder query = new StringBuilder();
		ParametroEntity entity = new ParametroEntity();
		List<ParametroEntity> lstParametros = null;
		try{
			query.append("select model  ");
			query.append("from ParametroEntity model ");
			query.append("where model.tipoparametro.codigotipoparametro = :codigoTipo");
			
			if (valorParametro != null)
				query.append(" and model.valornumerico = :valor ");
				
			
			if (valorParametro == null){
				entity = (ParametroEntity)getSession().createQuery(query.toString()).
					setParameter("codigoTipo", codigoTipo).list();
			}else{
				lstParametros = getSession().createQuery(query.toString()).
				setParameter("codigoTipo", codigoTipo).
				setParameter("valor", valorParametro).list();
				
				for(ParametroEntity parametro: lstParametros){
					entity = parametro;
				}
			}
			
			return entity;
		}catch(RuntimeException e){
			e.printStackTrace();logger.error(e);
			logger.fatal("findLast failed");
			throw e;
		}
	}
	
	public List<ParametroEntity> findByDescripcion(Object descripcion) {
		return findByProperty(DESCRIPCION, descripcion);
	}
	
	public List<ParametroEntity> findByValornumerico(Object valornumerico) {
		return findByProperty(VALORNUMERICO, valornumerico);
	}
	
	public List<ParametroEntity> findByValoralfanumerico(Object valoralfanumerico) {
		return findByProperty(VALORALFANUMERICO, valoralfanumerico);
	}
	
	public List<ParametroEntity> findByFlagactivo(Object flagactivo) {
		return findByProperty(FLAGACTIVO, flagactivo);
	}
	
	public List<ParametroEntity> findByUsuarioregistro(Object usuarioregistro) {
		return findByProperty(USUARIOREGISTRO, usuarioregistro);
	}
	
	public List<ParametroEntity> findByUsuariomodificacion(Object usuariomodificacion) {
		return findByProperty(USUARIOMODIFICACION, usuariomodificacion);
	}

	//gclv 16/09/2011
	//@SuppressWarnings("unchecked")
	public List<ParametroEntity> findByFiltro(ParametroBean filtro){
		logger.info("findByFiltro ParametroEntity instance");
		StringBuilder query = new StringBuilder();
		
		try{
			query.append("select model ");
			query.append("from  ParametroEntity model ");
			query.append("where 1 = 1 ");
			
			if (filtro.getCodigoparametro()!=null){
				query.append(" and model.codigoparametro = "+filtro.getCodigoparametro());
			}
			if (filtro.getFlagactivo()!=null){
				query.append(" and model.flagactivo = "+filtro.getFlagactivo());
			}
			if (filtro.getDescripcion()!=null){
				query.append(" and model.descripcion = '"+filtro.getDescripcion()+"'");
			}
			if (filtro.getValornumerico()!=null){
				query.append(" and model.valornumerico = "+filtro.getValornumerico());
			}
			if (filtro.getValoralfanumerico()!=null){
				query.append(" and model.valoralfanumerico = '"+filtro.getValoralfanumerico()+"'");
			}
			
			query.append(" order by model.codigoparametro ");
			
			return getSession().createQuery(query.toString()).list();
			
		}catch(RuntimeException e){
			logger.fatal("findByFiltro failed");
			throw e;
		}
	}	

	//@SuppressWarnings("unchecked")
	public List<ParametroEntity> findAll() {
		logger.info("finding all ParametroEntity instances");
		try {
			String queryString = "select model from ParametroEntity model";
			return getSession().createQuery(queryString).list();
		} catch (RuntimeException re) {
			logger.fatal("find all failed");
			throw re;
		}
	}
}